<template>
  <div class="account-container">
    <!-- 用户信息卡片 -->
    <el-card class="user-card">
      <div class="user-panel">
        <div class="user-info-container">
          <div class="avatar-section">
            <el-avatar :src="authData.user.avatar"  :size="80">
              {{ authData.user.name.charAt(0)  }}
            </el-avatar>
            <div class="user-details">
              <div class="user-id">工号: {{ authData.user.eid  }}</div>
              <h3 class="user-name">姓名：{{ authData.user.name  }}</h3>
            </div>
          </div>
          
          <div class="action-buttons">
            <el-button 
              v-if="authData.user.status  === 2" 
              type="primary" 
              size="small"
              @click="showLeaveDialog"
            >
              申请休假 
            </el-button>
            <el-button 
              class="quit-btn"
              type="warning"
              size="small"
              @click="handleLogout"
            >
              退出登录 
            </el-button>
          </div>
        </div>
      </div>
 
      <!-- 个人信息详情 -->
      <el-divider />
      <div class="info-grid">
        <div class="info-item">
          <div class="info-content">
            <div class="info-label">状态</div>
            <div class="info-value">
              <el-tag :type="statusTagType" size="small">
                {{ statusText }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="info-item">
          <div class="info-content">
            <div class="info-label">职位</div>
            <div class="info-value">{{ permissionText }}</div>

          </div>
        </div>
        <div class="info-item">
          <div class="info-content">
            <div class="info-label">就职时长</div>
            <div class="info-value">{{ employmentDuration }}</div>
          </div>
        </div>
      </div>
    </el-card>
 
    <!-- 账户安全卡片 -->
    <el-card class="security-card">
      <template #header>
        <div class="card-header">
          <el-icon><Lock /></el-icon>
          <span>账户安全</span>
        </div>
      </template>
      <div class="security-content">
        <div class="security-item">
          <div class="security-info">
            <el-icon><Key /></el-icon>
            <span>登录密码</span>
          </div>
          <el-button size="small" round @click="showPasswordDialog">修改</el-button>
        </div>
        <div class="security-item">
          <div class="security-info">
            <el-icon><ChatRound /></el-icon>
            <span>微信绑定</span>
          </div>
          <el-button 
            size="small" 
            round 
            :type="isWechatBound ? 'primary' : ''"
            @click="handleWechatBind"
          >
            {{ isWechatBound ? '已绑定' : '立即绑定' }}
          </el-button>
        </div>
      </div>
    </el-card>
 
    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="30%">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword"  type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword"  type="password" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword"  type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button round @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" round @click="submitPasswordChange">确认修改</el-button>
      </template>
    </el-dialog>
 
    <!-- 休假申请对话框 -->
    <el-dialog v-model="leaveDialogVisible" title="申请休假" width="40%">
      <el-form :model="leaveForm" :rules="leaveRules" ref="leaveFormRef">
        <el-form-item label="休假类型" prop="type">
          <el-select v-model="leaveForm.type"  placeholder="请选择休假类型">
            <el-option label="休假" value="annual"></el-option>
            <!-- <el-option label="病假" value="sick"></el-option>
            <el-option label="事假" value="personal"></el-option>
            <el-option label="调休" value="compensatory"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker 
            v-model="leaveForm.startDate" 
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker 
            v-model="leaveForm.endDate" 
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="休假原因" prop="reason">
          <el-input 
            v-model="leaveForm.reason" 
            type="textarea"
            :rows="3"
            placeholder="请详细说明休假原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button round @click="leaveDialogVisible = false">取消</el-button>
        <el-button type="primary" round @click="submitLeaveRequest">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Lock, Key, ChatRound } from '@element-plus/icons-vue'
 
const router = useRouter()
 
// 从authStore获取数据 
const authData = ref({
  token: '',
  user: {
    eid: '',
    name: '员工',
    permission: 0,
    status: 1,
    avatar: '',
    department: '一线员工',
    hireDate: null 
  }
})
 
// 密码修改相关 
const passwordDialogVisible = ref(false)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
 
// 微信绑定状态 
const isWechatBound = ref(false)
 
// 休假申请相关 
const leaveDialogVisible = ref(false)
const leaveForm = ref({
  type: '',
  startDate: '',
  endDate: '',
  reason: ''
})
 
const leaveRules = {
  type: [{ required: true, message: '请选择休假类型', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  reason: [{ required: true, message: '请输入休假原因', trigger: 'blur' }]
}
 
// 计算属性 
const statusText = computed(() => {
  const statusMap = ['离职', '休假', '在职']
  return statusMap[authData.value.user.status] || '未知状态'
})
 
const statusTagType = computed(() => {
  const types = ['danger', 'warning', 'success']
  return types[authData.value.user.status] || 'info'
})
 
const permissionText = computed(() => {
  const permissions = ['一线员工', '财务人员', '公司高层']
  return permissions[authData.value.user.permission] || '未知权限'
})
 
// 计算就职时间（精确到年月天和小时）
const employmentDuration = computed(() => {
  try {
    if (!authData.value.user.hireDate)  return "未知入职时间"
    
    const now = new Date()
    const hireDate = new Date(authData.value.user.hireDate) 
    
    // 检查日期有效性 
    if (isNaN(hireDate.getTime()))  return "无效入职日期"
    
    // 计算总毫秒差
    const diffMs = now - hireDate
    
    // 如果是未来时间 
    if (diffMs < 0) return "未入职"
    
    // 计算各个单位 
    let years = now.getFullYear()  - hireDate.getFullYear() 
    let months = now.getMonth()  - hireDate.getMonth() 
    let days = now.getDate()  - hireDate.getDate() 
    let hours = now.getHours()  - hireDate.getHours() 
    
    // 处理借位 
    if (hours < 0) {
      hours += 24
      days--
    }
    if (days < 0) {
      months--
      days += new Date(now.getFullYear(),  now.getMonth(),  0).getDate()
    }
    if (months < 0) {
      years--
      months += 12
    }
    
    // 构建结果字符串
    let result = ''
    if (years > 0) result += `${years}年`
    if (months > 0) result += `${months}月`
    if (days > 0) result += `${days}日`
    if (hours > 0) result += `${hours}时`
    
    // 如果是今天入职的特殊情况 
    if (years === 0 && months === 0 && days === 0) {
      return `今日入职 ${hours}小时`
    }
    
    return result || "0年0月0日0时"
  } catch (e) {
    console.error(" 计算就职时长出错:", e)
    return "计算错误"
  }
})
 
// 方法 
const showPasswordDialog = () => {
  passwordDialogVisible.value  = true 
}
 
const submitPasswordChange = () => {
  ElMessage.success(' 密码修改成功')
  passwordDialogVisible.value  = false
}
 
const showLeaveDialog = () => {
  leaveDialogVisible.value  = true 
}
 
const submitLeaveRequest = () => {
  ElMessageBox.confirm(' 确认提交休假申请吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(' 休假申请已提交，等待老板审批')
    leaveDialogVisible.value  = false
  }).catch(() => {
    ElMessage.info(' 已取消申请')
  })
}
 
const handleLogout = () => {
  ElMessageBox.confirm(' 确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    sessionStorage.removeItem('auth') 
    router.push('/elogin') 
    ElMessage.success(' 已退出登录')
  }).catch((action) => {
    if (action === 'cancel') {
      ElMessage.info(' 已取消退出登录')
    }
  })
}
 
const handleWechatBind = async () => {
  try {
    if (isWechatBound.value)  {
      await ElMessageBox.confirm(' 确定要解绑微信吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      isWechatBound.value  = false 
      ElMessage.success(' 微信解绑成功')
    } else {
      // 模拟微信绑定过程 
      ElMessage.info(' 请使用微信扫描二维码完成绑定')
      
      // 模拟API请求延迟 
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      isWechatBound.value  = true 
      ElMessage.success(' 微信绑定成功')
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info(' 已取消操作')
    } else {
      ElMessage.error(' 操作失败: ' + error.message) 
    }
  }
} 
 
// 初始化时从sessionStorage加载数据 
onMounted(() => {
  const auth = JSON.parse(sessionStorage.getItem('auth')) 
  if (auth) {
    console.log(' 从sessionStorage加载的hireDate:', auth.user.hireDate) 
    
    authData.value  = {
      token: auth.token, 
      user: {
        eid: auth.user.eid, 
        name: auth.user.name  || '员工',
        permission: auth.user.permission  ?? 0,
        status: auth.user.status  ?? 1,
        avatar: auth.user.avatar  || '',
        department: auth.user.department  || '一线员工',
        hireDate: auth.user.hireDate  || Date.now()  - 1000 * 60 * 60 * 24 * 90 // 默认3个月前 
      }
    }
    
    // 模拟检查微信绑定状态 
    isWechatBound.value  = Math.random()  > 0.5
  } else {
    ElMessage.warning(' 请先登录')
    router.push('/elogin') 
  }
})
 
// 密码验证规则 
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword)  {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
</script>



 
<style scoped>
.account-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}
 
.user-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
 
.user-info-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
 
.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}
 
.user-details {
  line-height: 1.6;
}
 
.user-name {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 500;
}
 
.user-id {
  font-size: 14px;
  color: #666;
}
 
.action-buttons {
  display: flex;
  gap: 10px;
}
 
.quit-btn {
  background-color: #ff9500;
  color: rgb(255, 255, 255);
  padding: 8px 16px;
  border: 0px;
  box-shadow: 3px 3px 1px 0px rgba(0, 0, 0, 0.08);
  z-index: 1;
}
.quit-btn:hover{
    background-color: #824e06d1;
    color: #ffffff;
    box-shadow: 3px 3px 1px 0px rgba(0, 0, 0, 0.296);
}

 
.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 10px;
}
 
.info-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
}
 
.info-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}
 
.info-label {
  font-size: 12px;
  color: #888;
  margin-bottom: 4px;
}
 
.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}
 
.security-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
 
.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  font-size: 16px;
}
 
.security-content {
  padding: 8px 0;
}
 
.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}
 
.security-item:last-child {
  border-bottom: none;
}
 
.security-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #555;
}
</style>